package com.lz.ccjdemo.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import java.util.HashMap;

/**
 * 动态权限获取
 */
public class PermissionsUtils {

    private int PERMISSION_REQUEST_CODE = 101;

    OnResultListener listener;

    public PermissionsUtils() {
    }

    public void requestPermissions(Activity activity, OnResultListener listener, String... permissions) {
        this.listener = listener;
        HashMap<String, String> noPermissList = new HashMap<>();
        for (String permission : permissions) {
            boolean isShow = ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
            if (isShow) {//已关闭提醒
                if (listener != null) {
                    listener.accept(false);
                }
                return;
            }
            // 检查是否具有权限
            if (ContextCompat.checkSelfPermission(activity, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                //无权限  可提醒
                noPermissList.put(permission, permission);
            }
        }
        if (noPermissList.size() == 0) {
            if (listener != null) {
                listener.accept(true);
            }
            return;
        }
        ActivityCompat.requestPermissions(activity, permissions, PERMISSION_REQUEST_CODE);
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE && listener != null) {
            boolean allPermissionsGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allPermissionsGranted = false;
                    break;
                }
            }
            if (allPermissionsGranted) {
                // 所有权限都被授予，可以执行相关操作
                listener.accept(true);
            } else {
                // 某些权限被拒绝，可以向用户解释为什么需要这些权限
                listener.accept(false);
            }
        }
    }

    public interface OnResultListener {
        void accept(boolean isSuccess);
    }
}
